package com.dream.common.utils;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

public class JsonUtils{

    public static ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }



    private final static Logger logger = LoggerFactory.getLogger(JsonUtils.class);

    /**
     * @return String json
     * @author Buke
     * @time 2014年11月3日 下午4:24:52
     * @Description: 序列化对象, 并且打印到控制台, (经常用于调试)
     *
     */
    public static String toStringPrint(Object object) {
        try {
            return  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return "";
        }
    }


    public static <T> List<T> parseArray(Object object, Class<T> clazz) {
        return parseArray(toJSONString(object), clazz);
    }


    /**
     * JSON字符串转对象
     *
     * @param text  JSON字符串
     * @param clazz 目标对象
     * @param <T>   泛型类型
     * @return 对象
     */
    public static <T> T parseObject(String text, Class<T> clazz) {
        try {
            return objectMapper.readValue(text, clazz);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            return null;
        }
    }

    /**
     * 对象转JSON字符串
     *
     * @param object 对象
     * @return JSON字符串
     */
    public static String toJSONString(Object object) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(object).replaceAll("\r|\n", "");
        } catch (JsonProcessingException e) {
            logger.error(e.getMessage(),e);
            return "";
        }
    }
}

